package com.pashanhoo.datastructure.linkedlist;

/**
 * @author 胡庆安
 * @version V1.0
 * @Package com.pashanhoo.datastructure.linkedlist
 * @date 2020/10/27 9:49
 * @Copyright © 2010-2020 爬山虎科技（扬州）股份有限公司
 */
public class SimpleList {

    //先初始化一个头结点
    private Node head = new Node("head");

    public void add(Node node){
        Node temp = head;
        while (temp.next!=null){
            temp = temp.next;
        }
        temp.next = node;
    }

    public int size(){
        int count = 0;
        Node temp = head;
        while (temp.next !=null){
            temp = temp.next;
            count ++;
        }
        return count;
    }

    public void reverse(){
        if (head.next == null){
            return;
        }
        //遍历原来的链表存放到新的链表
        Node temp = head.next;
        SimpleList simpleList = new SimpleList();
        Node newHead = simpleList.head;
        Node next = null;
        while (temp!=null){
            next = temp.next;//先暂时保存当前节点的下一个节点，因为后面需要使用
            temp.next = newHead.next;//将 temp 的下一个节点指向新的链表的最前端
            newHead.next = temp; //将 temp 连接到新的链表上
            temp = next;//让 temp 后移
        }
        head.next = newHead.next;

    }


    public static void main(String[] args) {
        Node node1 = new Node("111");
        Node node2 = new Node("222");
        Node node3 = new Node("333");
        Node node4 = new Node("444");
        SimpleList simpleList = new SimpleList();
        simpleList.add(node1);
        simpleList.add(node2);
        simpleList.add(node3);
        simpleList.add(node4);
        System.out.println(simpleList);
        System.out.println(simpleList.size());

        //查找单链表中的倒数第 k 个结点

        //单链表的反转
        simpleList.reverse();
        System.out.println(simpleList);

    }

}

class Node{
    public Node(String id){
        this.id = id;
    }
    public Node(){
    }
    String id;
    Node next;
}

